package org.ns.example.service;

import com.alibaba.fastjson.JSON;
import org.ns.example.dao.AccountDao;
import org.ns.example.pojo.Account;
import org.ns.example.pojo.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserService {
    @Autowired
    AccountDao accountDao;

    public ResponseEntity login(String username, String password, HttpServletRequest request) {
        Account account = accountDao.findById(username).get();
        if (account == null) {
            return ResponseEntity.newResponseEntity(1000001, "用户不存在");
        }
        if (password == null || !password.equals(account.getPassword())) {
            return ResponseEntity.newResponseEntity(1000002, "密码错误");
        }
        request.getSession().setAttribute("user", JSON.toJSONString(account));
        return ResponseEntity.newResponseEntity(0, "登录成功");
    }


    public boolean isLogin(HttpServletRequest request) {
        return request.getSession().getAttribute("user") != null;
    }

    public ResponseEntity getNotLoginResponse() {
        return ResponseEntity.newResponseEntity(1100001, "未登录");
    }
}
